﻿Imports DotSpatial.Data
Imports DotSpatial.Symbology

Public Class frmColorScheme

    Private dgvCategories As WRDB.Controls.DGVEditor
    Private rand As New Random(My.Computer.Clock.TickCount)
    Const SectionName = "CustomScheme"

    Private Sub frmColorScheme_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub frmColorScheme_Load(sender As Object, e As EventArgs) Handles Me.Load
        GetWindowPos(REGAPP, Me)
        dgvCategories = New WRDB.Controls.DGVEditor(dgCategories)
        With dgvCategories
            .SetHeadings("Min Value~Assigned Color", True, GISForm.AnimationInfo.CustomScheme.Count)
            .SetColumnFormat(WRDB.Controls.DGVEditor.enumColumnTypes.ColorPicker, 1, True)
            .DataGridView.Columns(0).DefaultCellStyle.Format = "0.000"
        End With
        FillGrid()
    End Sub

    Private Sub udNumCat_ValueChanged(sender As Object, e As EventArgs) Handles udNumCat.ValueChanged
        'delete if reduced
        If GISForm.AnimationInfo.CustomScheme.Count > udNumCat.Value Then GISForm.AnimationInfo.CustomScheme.RemoveRange(udNumCat.Value, GISForm.AnimationInfo.CustomScheme.Count - udNumCat.Value)
        'add if increased
        For i = GISForm.AnimationInfo.CustomScheme.Count To udNumCat.Value - 1
            Dim lst = CType(dgCategories.Columns(1), WRDB.Controls.DataGridViewColorPickerColumn).SortedColors
            GISForm.AnimationInfo.CustomScheme.Add(Tuple.Create(CDbl(i), lst(rand.Next(lst.Count - 1))))
        Next
        FillGrid()
    End Sub

    Private Sub FillGrid()
        With dgvCategories
            .DataGridView.Rows.Clear()
            For Each t In GISForm.AnimationInfo.CustomScheme
                .AddRowItems(t.Item1, t.Item2.Name)
            Next
        End With
        udNumCat.Value = GISForm.AnimationInfo.CustomScheme.Count
    End Sub

    Private Sub btnApply_Click(sender As Object, e As EventArgs) Handles btnApply.Click
        For r = 0 To dgCategories.Rows.Count - 1
            With dgCategories.Rows(r)
                GISForm.AnimationInfo.CustomScheme(r) = Tuple.Create(CDbl(.Cells(0).Value), Color.FromName(.Cells(1).Value))
            End With
        Next
        GISForm.AnimationInfo.OverrideScheme = True
        GISForm.RefreshPolygons()
        GISForm.DrawLegend()

    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Close()
    End Sub

    Private Sub lnkAutoFill_Click(sender As Object, e As EventArgs) Handles lnkAutoFill.Click
        'get the range of values for this var

        With GISForm.AnimationInfo
            '.MinValue = Double.MaxValue
            '.MaxValue = Double.MinValue
            'Dim vn As String = GISForm.cboVariable.Text
            '.MinValue = .dsData.MinValue(vn)
            '.MaxValue = .dsData.MaxValue(vn)

            Dim NumCat As Integer = udNumCat.Value
            .CustomScheme.Clear()

            For i As Integer = 0 To NumCat - 1
                Dim fillcolor As Color = ClosestKnownColor(GISForm.GradientColor(i * 1.0 / (NumCat - 1)))

                Dim value, catRange As Double
                catRange = (.MaxValue - .MinValue) / NumCat
                If Double.IsNaN(catRange) Or Double.IsInfinity(catRange) Then catRange = 100.0
                value = .MinValue + i * catRange
                .CustomScheme.Add(Tuple.Create(value, fillcolor))
            Next
            FillGrid()
        End With
    End Sub

    Private Function ClosestKnownColor(ExactColor As Color) As Color

        Dim dist As Double ' temporary distance measure
        Dim bestColor As Color
        Dim bestDist As Double = Double.MaxValue

        For Each c As Color In CType(dgCategories.Columns(1), WRDB.Controls.DataGridViewColorPickerColumn).SortedColors
            dist = (CInt(c.R) - ExactColor.R) ^ 2 + (CInt(c.G) - ExactColor.G) ^ 2 + (CInt(c.B) - ExactColor.B) ^ 2

            If dist < bestDist And c <> Color.Transparent Then
                bestColor = c
                bestDist = dist
            End If
        Next

        Return bestColor

    End Function

    Private Sub lnkRandomize_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkRandomize.LinkClicked
        Dim lst = CType(dgCategories.Columns(1), WRDB.Controls.DataGridViewColorPickerColumn).SortedColors
        For r As Integer = 0 To dgCategories.RowCount - 1
            dgCategories.Item(1, r).Value = lst(rand.Next(lst.Count - 1)).Name
        Next
    End Sub

    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
        Try

            With New OpenFileDialog
                .AddExtension = True
                .CheckFileExists = True
                .CheckPathExists = True
                .DefaultExt = ".GISLyr"
                .Filter = "GIS Layer Colors|*.GISLyr"
                .Multiselect = False
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    GISForm.AnimationInfo.CustomScheme.Clear()
                    With New IniFile.clsIniFile(.FileName, False)
                        Dim Version As Integer = Val(.GetKeyText(SectionName, "Version", 1))
                        For Each s In .GetKeyNames(SectionName)
                            GISForm.AnimationInfo.CustomScheme.Add(Tuple.Create(CDbl(s), Color.FromName(.GetKeyText(SectionName, s))))
                        Next
                    End With
                    FillGrid()
                End If
                .Dispose()
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Try

            With New SaveFileDialog
                .AddExtension = True
                .CheckFileExists = False
                .CheckPathExists = True
                .CreatePrompt = False
                .DefaultExt = ".GISLyr"
                .Filter = "GIS Layer Colors|*.GISLyr"
                .OverwritePrompt = True
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    If My.Computer.FileSystem.FileExists(.FileName) Then My.Computer.FileSystem.DeleteFile(.FileName)
                    With New IniFile.clsIniFile(.FileName, True)
                        .SetKeyText(SectionName, "Version", "1")
                        For r = 0 To dgCategories.Rows.Count - 1
                            .SetKeyText(SectionName, dgCategories.Rows(r).Cells(0).FormattedValue, dgCategories.Rows(r).Cells(1).Value)
                        Next
                        .Save()
                    End With
                End If
                .Dispose()
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub
End Class